import https from 'https';
import fs from 'fs';
import path from 'path';

/**
 * 下载网络图片到本地
 * @param {string} url - 图片URL地址
 * @param {string} saveDir - 保存目录路径
 * @param {string} [filename] - 自定义文件名（可选）
 * @returns {Promise<string>} 保存后的完整路径
 */
export async function downloadImage(url, saveDir, filename = null) {
  // 自动生成文件名
  if (!filename) {
    const ext = path.extname(new URL(url).pathname) || '.jpg';
    filename = `img_${Date.now()}${ext}`;
  }

  const filePath = path.join(saveDir, filename);
  const file = fs.createWriteStream(filePath);

  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      if (response.statusCode !== 200) {
        reject(new Error(`下载失败，状态码: ${response.statusCode}`));
        return;
      }

      response.pipe(file);
      
      file.on('finish', () => {
        file.close();
        resolve(filePath);
      });
      
      file.on('error', (err) => {
        fs.unlinkSync(filePath);
        reject(err);
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
}